from ToDo.todoAppwithMysql.storage_mysql import TodoStorgeWithMySQL
from ToDo.todoAppwithMysql.todo import Todo
from flask import Flask,request

app = Flask(__name__)
manager=TodoStorgeWithMySQL()

app.config['JSON_AS_ASCII'] = False

@app.route("/", methods=['GET'])
def hello():
    return "欢迎使用记事本"

@app.route("/todos", methods=['GET'])
def list_todos():
     return {"todos":[x.__dict__ for x in manager.get_list()]}

@app.route("/create", methods=['POST'])
def create():
    if 'title' not in request.form:
        # title 表示待办事项内容
        return '参数错误，必须提供 title 参数', 400
    todo = manager.creat(request.form["title"])
    return todo.__dict__

@app.route("/delete", methods=['POST'])
def delete():
    if "id" not in request.form:
        return '参数错误，必须提供 title 参数', 400
    else:
        return {"todos":[x.__dict__ for x in manager.delete(int(request.form["id"]))]}

@app.route("/completed", methods=['GET'])
def mark_completed():
    if "id" not in request.args:
        return "参数错误，必须提供 id 参数", 401

    else:
        return {"todos": [x.__dict__ for x in manager.mark_completed(int(request.args["id"]))]}

@app.route("/things",methods=['GET'])
def things():
    if request.args.get('completed')=='1':
        return {"todos":[x.__dict__ for x in manager.yescompleted()]}
    elif request.args.get('completed')=='all':
        return {"todos":[x.__dict__ for x in manager.get_list()]}
    else:
        return {"todos": [x.__dict__ for x in manager.nofinished()]}


if __name__== "__main__":
    app.run()